from django.contrib import admin

# Register your models here.
from django.db.models import F

from blog.models import Article, LogInfo, CommentInfo

admin.site.site_title  = '博客系统'    #设置title
admin.site.site_header = '博客管理系统' #设置header
admin.site.index_title = '后台主页'    #设置index_title

# 注册ModelAdmin类(文章)
@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
    list_display = ["category", "title", "author", "abstract", "user", "c_time"]

    def has_delete_permission(self, request, obj=None):
        return False

    list_display_links = ["title"]

    fieldsets = (
        ("基本信息", {'fields':
                      ["title", ("author", "category"), "abstract", "content"]
                    }),
        ("交互信息", {'fields':
                      [("like_num", "against_num"), ("reply_num", "read_num")]
                    })
    )

    list_max_show_all = 100
    list_per_page = 5
    readonly_fields = ("like_num", "against_num", "reply_num", "read_num")
    search_fields = ["title", "category"]

# 注册ModelAdmin类(文章评论)
@admin.register(CommentInfo)
class CommentInfoAdmin(admin.ModelAdmin):
    list_display = ["article", "content", "user", "c_time"]
    fields = ("article", "content",)
    raw_id_fields = ("article",)

    def has_delete_permission(self, request, obj=None):
        return False

    search_fields = ("article", "content",)
    list_per_page = 5
    ordering = ("-c_time", "article")

    def save_model(self, request, obj, form, change):
        if not change:  # 在更新操作下不对reply_num加1
            obj.user = request.user # 获取当前用户对象
            Article.objects.filter(pk=obj.article.id). \
                update(reply_num=F("reply_num") + 1);  # 使用F对象查询方法
        super(CommentInfoAdmin, self).save_model(request, obj, form, change)


# 注册ModelAdmin类(评论日志)
@admin.register(LogInfo)
class LogInfoAdmin(admin.ModelAdmin):
    list_display = ["article", "types", "user", "c_time"]

    # 禁用点评日志的修改功能
    def has_change_permission(self, request, obj=None):
        return False

    # 禁用点评日志的删除功能
    def has_delete_permission(self, request, obj=None):
        return False

    search_fields = ["types", "article__title"]
    fields = ["article", "types"]

    def save_model(self, request, obj, form, change):
        obj.user = request.user  # 获取当前用户对象
        t = obj.types # 获取评论类别[(0, "阅读"), (1, "点赞"), (2, "拍砖")]
        if t == 0: # 阅读类别时
            # 获取文章对象，然后将阅读数增加1
            Article.objects.filter(pk=obj.article.id).update(read_num=F('read_num') + 1)
        elif t == 1: # 点赞类别时
            Article.objects.filter(pk=obj.article.id).update(read_num=F('like_num') + 1)
        else: # 拍砖类别时
            Article.objects.filter(pk=obj.article.id).update(read_num=F('against_num') + 1)
        super(LogInfoAdmin, self).save_model(request, obj, form, change)
